package com.neusoft.resturant.interceptor;

import com.alibaba.fastjson2.JSON;
import com.neusoft.resturant.common.exception.BizException;
import com.neusoft.resturant.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

   @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    String token = String.valueOf(request.getSession().getAttribute("token"));
    if (token == null) {
        throw new BizException(401, "认证失败，非法用户");
    }
    String userJson = (String) redisTemplate.opsForValue().get(token);
    if (userJson == null) {
        throw new BizException(401, "认证失败，非法用户");
    }
    SysUser curUser = JSON.parseObject(userJson, SysUser.class);
    request.setAttribute("userId", curUser.getUserId());
    return true;
}

}
